package my.jwds.p954;

import java.util.TreeMap;

public class CanReorderDoubled {

    public static void main(String[] args) {

        CanReorderDoubled obj = new CanReorderDoubled();
        long start = System.currentTimeMillis();
        System.out.println(obj.canReorderDoubled(new int[]{-5,-2}));
        System.out.println("运行时间:" + (System.currentTimeMillis() - start));
    }


    public boolean canReorderDoubled(int[] arr) {
        TreeMap<Integer,Integer> treeMap = new TreeMap<>();
        for (int i : arr) {
            Integer count = treeMap.get(i);
            if (count == null) count = 0;
            treeMap.put(i,count+1);
        }

        while(!treeMap.isEmpty()){
            Integer num = treeMap.firstKey(),
                    count = treeMap.firstEntry().getValue(),
                    targetNum = num >=0 ? num*2 : num%2 == -1? Integer.MAX_VALUE:num/2,
                    targetCount = treeMap.get(targetNum);
            if (targetNum == 0){
                targetCount = count-1;
            }
            if (targetCount == null || targetCount == 0){
                return false;
            }

            if (count <= 1)treeMap.remove(num);
            else treeMap.put(num,count-1);
            if (targetCount <= 1)treeMap.remove(targetNum);
            else treeMap.put(targetNum,targetCount-1);
        }

        return true;
    }

}